package com.ihome.android.market2.frag;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ihome.android.EAFragment;
import com.ihome.android.academy.AppMgrActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.image.util.Version;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetInstalledAppTask;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.AppInstalledItem;
import com.ihome.android.util.AppMgr;
import com.ihome.android.util.PkgSizeObserver;
import com.ihome.android.util.log.LogUtil;

public class InstalledAppFragment extends EAFragment implements OnClickListener, OnKeyListener {
	private final String		TAG								= InstalledAppFragment.class.getSimpleName();
	private View				fragview;

	private InstalledAppAdapter	mAdapter;
	private List<AppInfo>		mListAppPerPage = new ArrayList<AppInfo>();
	private List<AppInfo>		mListAppTotal;

	@EAInjectView(id = R.id.gv_mgr_app)
	private GridView			mGridView;
	@EAInjectView(id = R.id.tv_page_pre)
	private TextView			tv_page_pre;
	@EAInjectView(id = R.id.tv_page_next)
	private TextView			tv_page_next;
	
	@EAInjectView(id = R.id.ll_data_tip)
	private RelativeLayout ll_data_tip;

	/** 该分类当前页数 */
	private int					mCurPage						= 1;
	/** 该分类APP总数 */
	private int					mAppNum							= 0;
	/** 每页展示的APP数量 */
	private final int			APPNUM_PER_PAGE					= 9;

	private final int			MSG_SPINEER_APP_LIST_REFRESH	= 3;
	private final int			MSG_SHOW_PREVIEW_PAGE			= 6;
	private final int			MSG_SHOW_NEXT_PAGE				= 8;

	private Handler				mHandler;

	private ImageLoader			imageLoader;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SPINEER_APP_LIST_REFRESH:
					mCurPage = 1;
					// setPageLine();
					getInstalledAppList();
					break;
				case MSG_SHOW_NEXT_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_NEXT_PAGE ------");
					if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
						mCurPage++;
						mAdapter.setCurPage(mCurPage);
						setPageLine();
					}
					break;
				case MSG_SHOW_PREVIEW_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_PREVIEW_PAGE ------");
					if (mCurPage > 1) {
						mCurPage--;
						mAdapter.setCurPage(mCurPage);
						setPageLine();
					}
					break;

				default:
					break;
				}
			}
		};
	}

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		LogUtil.i(TAG, "--> onAttach");

		imageLoader = ImageLoaderFactory.create(getActivity());
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.icon_default);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		procHandler();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, " -->  onCreateView()");
		fragview = (RelativeLayout) inflater.inflate(R.layout.frag_installed_app, container, false);

		return fragview;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() ");
		//focusView();
	}

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		LogUtil.i(TAG, " -->  setArguments()");
	}

	public void initData() {
		LogUtil.w(TAG, " -->  initData() ");
		if (mListAppTotal == null || mListAppTotal.size() == 0) {
			getInstalledAppList();
		}
		setPageLine();
	}

	public void focusGridView() {
		LogUtil.w(TAG, " -->  focusGridView() ");

		mAdapter.notifyDataSetChanged();
		mGridView.requestFocus();
		//mAdapter.requestFocus();
	}

	private void init() {
		LogUtil.i(TAG, " -->  init()");

		mGridView.setFocusable(true);
		mGridView.setOnKeyListener(this);
		
		tv_page_pre.setOnClickListener(this);
		tv_page_next.setOnClickListener(this);

		initData();
	}

	/**
	 * 设置页数和APP总数
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void setPageLine() {
		mAppNum = mListAppTotal.size();
		((AppMgrActivity)getActivity()).setPageLine(mCurPage, mAppNum, 0);
		
		if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
			tv_page_next.setVisibility(View.VISIBLE);
		}
		
		if (mCurPage * APPNUM_PER_PAGE >= mAppNum && tv_page_next.getVisibility() == View.VISIBLE) {
			mGridView.requestFocus();
			tv_page_next.setVisibility(View.GONE);
		}

		if (mCurPage == 1 && tv_page_pre.getVisibility() == View.VISIBLE) {
			mGridView.requestFocus();
			tv_page_pre.setVisibility(View.GONE);
		}

		if (mCurPage > 1) {
			tv_page_pre.setVisibility(View.VISIBLE);
		}
		
	}

	private void getInstalledAppList() {
		LogUtil.i(TAG, " -->  getCategoryList()");

		int startIndex = (mCurPage - 1) * APPNUM_PER_PAGE;
		if (mListAppTotal == null)
			mListAppTotal = new ArrayList<AppInfo>();
		if (startIndex == 0)
			mListAppTotal.clear();

		new GetInstalledAppTask(getActivity(), this).execute(new Bundle());
	}
	
	/** 当前Item的位置  */
	int mFocusedPosition = -1;
	/**
	 * 判断是否在GridView的第一行
	 * @see [类、类#方法、类#成员]
	 */
	public boolean isOnFirstLine(){
		if(mFocusedPosition == 0 || mFocusedPosition == 1 || mFocusedPosition == 2){
			return true;
		}
		return false;
	} 
	
	/**
	 * 当焦点不在当前Fragment的时候，把所欲Item的恢复成最初状态
	 * @see [类、类#方法、类#成员]
	 */
	public void recovery(){
		mAdapter.setFocusedPosition(-1);
	}
	
	public class InstalledAppAdapter extends BaseAdapter {
		private LayoutInflater		mInflater;
		private Context				context;

		private AppInstalledItem	firstAppItem;
		private AppInstalledItem	focusedAppItem;

		public InstalledAppAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
			setCurPage(1);
		}

		public void setCurPage(int mCurPage) {
			
			int total = mListAppTotal.size() ;
			int start = (mCurPage-1)*APPNUM_PER_PAGE;
			int end = start + APPNUM_PER_PAGE;
			mListAppPerPage.clear();
			for(int i = start; i < total && i < end ; i++){
				mListAppPerPage.add(mListAppTotal.get(i));
			}
			
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {

			return mListAppPerPage.size();
		}

		@Override
		public Object getItem(int position) {
			
			return mListAppPerPage.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		};

		public void requestFocus() {
			if(firstAppItem != null)
				firstAppItem.requestFocus();
			else
				LogUtil.e(TAG, "firstAppItem is NULL ");
//			if (focusedAppItem != null && focusedAppItem.position < mListAppPerPage.size()) {
//				focusedAppItem.requestFocus();
//			}
//			else if(focusedAppItem.position >= mListAppPerPage.size()){
//				firstAppItem.requestFocus();
//			}
//			else {
//				LogUtil.e(TAG, "firstAppItem is NULL ");
//			}
		}

		public void setFocusedPosition(int position) {
			mFocusedPosition = position;
			LogUtil.v(TAG, "setFocusedPosition() position = " + position);
			for (int i = 0, size = mListAppPerPage.size(); i < size; i++) {
				if (i != position) {
					mListAppPerPage.get(i).setHasFocus(false);
				}
				else {
					mListAppPerPage.get(i).setHasFocus(true);
				}
			}
			
			if(((AppMgrActivity)getActivity()).getCurPosition() == 0 || !Version.hasKitKat()){
				notifyDataSetChanged();
			}
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			AppInstalledItem appItem;

			AppInfo appInfo = (AppInfo) getItem(position);

			if (null == convertView) {
				appItem = new AppInstalledItem(context, imageLoader);
				convertView = appItem.getView();
				convertView.setTag(appItem);
			}
			else {
				appItem = (AppInstalledItem) convertView.getTag();
			}

			appItem.initView(this, appInfo, position);

			if (appInfo.isHasFocus()) {
				appItem.hasFocus();
				focusedAppItem = appItem;
			}
			else {
				appItem.recovered();
			}
			
			if(position == 0){
				firstAppItem = appItem;
			} 

			appItem.setOnKeyListener(InstalledAppFragment.this);

			return convertView;
		}
	}

	/**
	 * 成功获取应用列表回调方法
	 * 
	 * @param mAppList
	 * @param appsNum
	 */
	public void getAppSuccess(List<AppInfo> mAppList, int appsNum) {
		mAppNum = appsNum;
		mListAppTotal = mAppList;

		mAdapter = new InstalledAppAdapter(getActivity());
		mGridView.setAdapter(mAdapter);

		if(mListAppTotal.size()>0){
			ll_data_tip.setVisibility(View.GONE);
		}else{
			ll_data_tip.setVisibility(View.VISIBLE);
		}
		setPageLine();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_page_pre:
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			break;
		case R.id.tv_page_next:
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
//		LogUtil.v(TAG, " --> onKey() mGridView.hasFocus() = " + mGridView.hasFocus());
//		LogUtil.d(TAG, " --> onKey() mInstallAppFrag.isOnFirstLine() =" + isOnFirstLine());
//		LogUtil.d(TAG, " --> onKey() keyCode=" + keyCode + "; event.getAction()=" + event.getAction());

		if (isOnFirstLine() && (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction() == KeyEvent.ACTION_DOWN)) {
			recovery();
			((AppMgrActivity)getActivity()).titleFocus();
			return true;
		}

		if (keyCode == KeyEvent.KEYCODE_PAGE_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			return true;
		}
		else if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			return true;
		}
		
		if((keyCode == KeyEvent.KEYCODE_PAGE_UP || keyCode == KeyEvent.KEYCODE_PAGE_DOWN) && event.getAction() == KeyEvent.ACTION_UP ){
			if(mGridView.hasFocus()){
				mAdapter.requestFocus();
			}
		}
		
		return false;
	}

	public void uninstallationCheck(String pkgName) {
		LogUtil.v(TAG, " -->  uninstallationCheck() pkgName = " + pkgName);
		for (AppInfo appinfo : mListAppTotal) {
			if (appinfo.getPkgName().equals(pkgName)) {
				mListAppTotal.remove(appinfo);
				break;
			}
		}
		if(mListAppTotal!=null && mListAppTotal.size()%9 ==0 && mCurPage>1){
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
		}else{
			mAdapter.setCurPage(mCurPage);
			setPageLine();
			focusGridView();
		}

		if(mListAppTotal.size() == 0){
			((AppMgrActivity)getActivity()).titleFocus();
		}
		if(mListAppTotal.size()>0){
			ll_data_tip.setVisibility(View.GONE);
		}else{
			ll_data_tip.setVisibility(View.VISIBLE);
		}
	}
	
	/**
	 * 应用安装成功后的回调方法，需要清除已安装列表
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	public void installationCheck(String pkgName) {
		try {
			
			boolean isExist = false;
			for (AppInfo app : mListAppTotal) {
				if (app.getPkgName().equals(pkgName)) {
					isExist = true;
					break;
				}
			}
			
			if(!isExist){
				AppInfo appinfo = AppMgr.getInstance().loadAppByPkgName(getActivity(), pkgName);
				AppMgr.queryPkgSize(getActivity(), appinfo, new PkgSizeObserver(appinfo));
				mListAppTotal.add(appinfo);
				mAdapter.setCurPage(mCurPage);
				setPageLine();
			}
			if(mListAppTotal.size()>0){
				ll_data_tip.setVisibility(View.GONE);
			}else{
				ll_data_tip.setVisibility(View.VISIBLE);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
